package cn.k.service.impl;

import cn.k.domain.Role;
import cn.k.mapper.RoleMapper;
import cn.k.qo.QueryObject;
import cn.k.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional
    public void save(Role role, Long[] permissionIds) {
        //除了往角色表存入数据,还往角色权限中间表存入关系数据
         roleMapper.insert(role);
         if (permissionIds!=null && permissionIds.length>0){
             for (Long permissionId : permissionIds) {
                 roleMapper.insetRelation(role.getId(),permissionId);
             }
         }
    }

    @Override
    public void delete(Long id) {
        roleMapper.deleteByPrimaryKey(id);
        roleMapper.deleteRelation(id);

    }

    @Override
    @Transactional
    public void update(Role role, Long[] permissionIds) {
        //除了修改角色的名字和缩写以外,还要到中间表删除之前给这个角色的权限,再重新加给新分配的权限给角色
        roleMapper.updateByPrimaryKey(role);
        roleMapper.deleteRelation(role.getId());
        if (permissionIds!=null && permissionIds.length>0){
            for (Long permissionId : permissionIds) {
                roleMapper.insetRelation(role.getId(),permissionId);
            }
        }

    }

    @Override
    public Role get(Long id) {
        Role role = roleMapper.selectByPrimaryKey(id);
        return role;
    }

    @Override
    public List<Role> selectAll() {
        List<Role> roles = roleMapper.selectAll();
        return roles;
    }


    @Override
    public List<Role> selectForList(QueryObject qo) {
        List<Role> roles = roleMapper.selectForList(qo);
        return roles;
    }

    @Override
    public PageInfo<Role> query(QueryObject qo) {
        //告诉插件我们查询第几页,每页多少条
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        //查询当前页数据
        List<Role> roles = roleMapper.selectForList(qo);
        return new PageInfo<>(roles);
    }

    @Override
    public List<Role> queryByEmployeeId(Long employeeId) {
        return roleMapper.selectByEmployeeId(employeeId);
    }

    @Override
    public List<String> queryRoleByEmployee(Long id) {
        return roleMapper.selectRoleByEmployee(id);
    }
}
